package com.shen.GOF.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class LazyMan {


    private LazyMan() {
//        synchronized (LazyMan.class) {
//            if (lazyMan == null) {
//                throw new RuntimeException("Don't want to change God");
//            }
//        }
    }

    private volatile static LazyMan lazyMan;

    //双重检测锁模式的懒汉式 DCL懒汉式
    public static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();//不是一个原子性操作
                    /*
                     * 1.分配内存空间
                     * 2.执行构造方法，初始化对象
                     * 3.把这个对象指向这个空间
                     * */
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        // LazyMan instance = LazyMan.getInstance();
//        Field field = LazyMan.class.getDeclaredField("bin");
//        field.setAccessible(true);
//        field.set("bin", false);

        Constructor<? extends LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);//获得空参构造器
        constructor.setAccessible(true);//无视私有化
        LazyMan instance1 = constructor.newInstance();
        LazyMan instance = constructor.newInstance();
        System.out.println(instance);
        System.out.println(instance1);

    }


    //多线程并发
//    public static void main(String[] args) {
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                LazyMan.getInstance();
//            }).start();
//        }
//    }
}
